//
//  CLViewController.m
//  CL1024
//
//  Created by liu nian on 13-1-28.
//  Copyright (c) 2013年 liunian. All rights reserved.
//

#import "CLViewController.h"
#import "TFHpple.h"
#import "CLPostContentViewController.h"
#import "CLTool.h"
#import "MBProgressHUD.h"
#import "CLColor.h"
#import "CLConst.h"
#import "PrettyKit.h"
#import "CLAppDelegate.h"
#import "CLSlideEffectWindow.h"

#import "CLNewPostContentViewController.h"


#define KEY_HREF @"href"
#define KEY_TEXT @"text"

@interface CLViewController (){
    int currentPage; //当前页
}

@property (retain, nonatomic) IBOutlet PrettyToolbar *toolbar;
@property (retain,nonatomic) NSMutableArray *posts; //帖子标题
@property (retain,nonatomic) NSMutableArray *hrefs; //帖子链接
@property (retain,nonatomic) NSMutableArray *author;//作者
@property (retain,nonatomic) NSMutableArray *postDate;//发帖日期
@property (retain,nonatomic) NSMutableArray *replyNum; //回帖数
@property (retain,nonatomic) TFHpple *doc;


-(IBAction)nextPage;
-(IBAction)previousPage;

@end



@implementation CLViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        //首先读取配置中心的URL
        self.clServerUrl = [[NSUserDefaults  standardUserDefaults] objectForKey:@"caoliuServerURL"];
        if (self.clServerUrl == nil) {
            self.clServerUrl = CL_URL;
            
            self.posts = [NSMutableArray array];
            self.author = [NSMutableArray array];
            self.hrefs = [NSMutableArray array];
            self.postDate = [NSMutableArray array];
            self.replyNum = [NSMutableArray array];
            
            currentPage = 1;
        }
    }

    return self;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
      
    
    
    [self.navigationController setValue:[[[PrettyNavigationBar alloc] init] autorelease] forKey:@"navigationBar"];
    PrettyNavigationBar *navBar = (PrettyNavigationBar *)self.navigationController.navigationBar;
   // 导航栏颜色设置
    navBar.topLineColor = [UIColor colorWithHex:0x000000];
    navBar.gradientStartColor = [UIColor colorWithHex:0x000000];
    navBar.gradientEndColor = [UIColor colorWithHex:0x006699];
    navBar.bottomLineColor = [UIColor colorWithHex:0x004D7F];
    navBar.tintColor = navBar.gradientEndColor;
    navBar.roundedCornerRadius = 8;
    //工具栏颜色设置
    self.toolbar.topLineColor =  [UIColor colorWithHex:0x004D7F];
    self.toolbar.gradientStartColor = [UIColor colorWithHex:0x006699];
    self.toolbar.gradientEndColor = [UIColor colorWithHex:0x000000]; 
    self.toolbar.bottomLineColor = [UIColor colorWithHex:0x000000];
    self.toolbar.tintColor = navBar.gradientEndColor;

        UILabel *label = [[[UILabel alloc] initWithFrame:CGRectZero] autorelease];
        label.backgroundColor = [UIColor clearColor];
        label.font = kHSCNBoldFont18;
        label.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5];
        label.textAlignment = UITextAlignmentCenter;
        label.textColor = [UIColor whiteColor];
        label.text = self.title;
        self.navigationItem.titleView = label;
        [label sizeToFit];
    //for ios5
    [self.postsTableView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"background.png"]]];
    //for ios6
    [self.postsTableView setBackgroundView:[[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"background.png"]] autorelease]];
    [NSThread detachNewThreadSelector:@selector(searchesLinkText) toTarget:self withObject:nil];

  }


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}
#pragma mark - 
#pragma mark  UITableViewDataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.posts count];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"postCell";
    PrettyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) {
        cell = [[[PrettyTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];

         cell.cornerRadius = 10;
         cell.tableViewBackgroundColor = tableView.backgroundColor;
        
        //今日贴 
        UILabel *newPromptLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 30, 10)];
        newPromptLabel.text = @"今日贴";
        newPromptLabel.font = kHSCNBoldFont10;
        newPromptLabel.textColor = [UIColor whiteColor];
        newPromptLabel.backgroundColor = [UIColor redColor];
        newPromptLabel.tag = 1110;
        [cell.contentView addSubview:newPromptLabel];
        [newPromptLabel setHidden:YES];
        [newPromptLabel release];
        
        
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 2, 280, 50)];
        titleLabel.font =kHSCNBoldFont14;
        titleLabel.lineBreakMode = UILineBreakModeWordWrap;
        titleLabel.numberOfLines = 0;
        titleLabel.tag = 1111;
        titleLabel.textColor = [UIColor darkGrayColor];
        titleLabel.backgroundColor = [UIColor clearColor];
        [cell.contentView addSubview:titleLabel];
        [titleLabel release];
        
        //作者标题
        UILabel *athorLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 50, 24, 10)];
        athorLabel.text = @"作者:";
        athorLabel.font =kHSCNBoldFont10;
        athorLabel.textColor = [UIColor grayColor];
        athorLabel.tag = 1112;
        athorLabel.backgroundColor = [UIColor clearColor];
        [cell.contentView addSubview:athorLabel];
        [athorLabel release];
        //作者
        UILabel *athorNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(34, 50,80,10)];
        athorNameLabel.font =kHSCNBoldFont10;
        athorNameLabel.textColor = [UIColor grayColor];
        athorNameLabel.tag = 1113;
        athorNameLabel.backgroundColor = [UIColor clearColor];
        [cell.contentView addSubview:athorNameLabel];
        [athorNameLabel release];
        
        //回帖数标题
        UILabel *replyNumTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(110, 50, 24, 10)];
        replyNumTitleLabel.text = @"回帖:";
        replyNumTitleLabel.font =kHSCNBoldFont10;
        replyNumTitleLabel.textColor = [UIColor grayColor];
        replyNumTitleLabel.backgroundColor = [UIColor clearColor];
        [cell.contentView addSubview:replyNumTitleLabel];
        [replyNumTitleLabel release];
       //回帖数
        UILabel *replyNumLabel = [[UILabel alloc] initWithFrame:CGRectMake(134, 50, 30, 10)];
        replyNumLabel.font =kHSCNBoldFont10;
        replyNumLabel.textColor = [UIColor grayColor];
        replyNumLabel.tag = 1114;
        replyNumLabel.backgroundColor = [UIColor clearColor];
        [cell.contentView addSubview:replyNumLabel];
        [replyNumLabel release];
        
       //发表日期标题
        UILabel *postDateTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(170, 50, 55, 10)];
        postDateTitleLabel.text = @"发表日期:";
        postDateTitleLabel.font =kHSCNBoldFont10;
        postDateTitleLabel.textColor = [UIColor grayColor];
        postDateTitleLabel.backgroundColor = [UIColor clearColor];
        [cell.contentView addSubview:postDateTitleLabel];
        [postDateTitleLabel release];
        
        //发表日期
        UILabel *postDateLabel = [[UILabel alloc] initWithFrame:CGRectMake(215, 50, 100, 10)];
        postDateLabel.font =kHSCNBoldFont10;
        postDateLabel.textColor = [UIColor grayColor];
        postDateLabel.tag = 1115;
        postDateLabel.backgroundColor = [UIColor clearColor];
        [cell.contentView addSubview:postDateLabel];
        [postDateLabel release];

        

        cell.selectionGradientStartColor =[UIColor colorWithHex:0xE2E2E2];
        cell.selectionGradientEndColor = [UIColor colorWithHex:0xE2E2E2];
    }
    [cell prepareForTableView:tableView indexPath:indexPath];
//    cell.postTitle.font = kHSCNBoldFont16;
//    cell.textLabel.text = [self.posts objectAtIndex:[indexPath row]] ;
   
    UILabel *newPromptLabel = (UILabel *)[cell.contentView viewWithTag:1110];
 
    NSDateFormatter *dataFormat = [[[NSDateFormatter alloc] init] autorelease];
    [dataFormat setDateFormat:@"yyyy-MM-dd"];
    NSString *dataString =  [dataFormat stringFromDate:[NSDate date]];
    if ([dataString isEqualToString:[self.postDate objectAtIndex:[indexPath row]]]) {
        newPromptLabel.hidden = NO;
    }else{
        newPromptLabel.hidden = YES;
    }
    
    UILabel *titleLabel =(UILabel *)  [cell.contentView viewWithTag:1111];
    titleLabel.text =[self.posts objectAtIndex:[indexPath row]] ;
    
    UILabel *athorNameLabel = (UILabel *) [cell.contentView viewWithTag:1113];
    athorNameLabel.text = [self.author objectAtIndex:[indexPath row]];
    
    UILabel *replyNumLabel = (UILabel *) [cell.contentView viewWithTag:1114];
    replyNumLabel.text = [self.replyNum objectAtIndex:[indexPath row]];
    
    UILabel *postDateLabel = (UILabel *) [cell.contentView viewWithTag:1115];
    postDateLabel.text = [self.postDate objectAtIndex:[indexPath row]];

    
    return cell;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:TRUE];
    
    
    NSString *postFullURL = [NSString stringWithFormat:@"%@/%@",self.clServerUrl,[self.hrefs objectAtIndex:[indexPath row]]];
    CLPostContentViewController *vc = [[CLPostContentViewController alloc] initWithNibName:@"CLPostContentViewController" bundle:nil];
    vc.title = self.title;
    vc.fullURL = postFullURL; //URL地址
    vc.postTitle = [self.posts objectAtIndex:[indexPath row]];//帖子名称
    [self.navigationController pushViewController:vc animated:YES];
    [vc release];

    
    /*
    NSString *postFullURL = [NSString stringWithFormat:@"%@/%@",self.clServerUrl,[self.hrefs objectAtIndex:[indexPath row]]];
    CLPostContentViewController *vc = [[[CLPostContentViewController alloc] initWithNibName:@"CLPostContentViewController" bundle:nil] autorelease];
    vc.title = self.title;
    vc.fullURL = postFullURL; //URL地址
    vc.postTitle = [self.posts objectAtIndex:[indexPath row]];//帖子名称
    
//    CLNewPostContentViewController *vc = [[[CLNewPostContentViewController alloc] init] autorelease];
    
    CLAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
    CLSlideEffectWindow *contentWindow = delegate.contentWindow;
    contentWindow.prevWindow = delegate.window;
    [contentWindow setRootViewController:vc];
    [contentWindow makeKeyAndVisible];
    
    [UIView animateWithDuration:0.3 animations:^{
        [contentWindow setFrame:[[UIScreen mainScreen] bounds]];
        
    } completion:^(BOOL finished) {
    }];
     */
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 65.f;
//    return tableView.rowHeight + [PrettyTableViewCell tableView:tableView neededHeightForIndexPath:indexPath];
}

#pragma mark -
#pragma mark UIAlertDelegate
/*
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    //因为网络原因无法显示时，用户选择重试
    if (buttonIndex == 0) {
        [NSThread detachNewThreadSelector:@selector(searchesLinkText) toTarget:self withObject:nil];
    }
}
*/

#pragma mark -
-(void)searchesLinkText
{
    //收集前先清空数组
    if ([self.posts count] != 0) {
        [self.posts removeAllObjects];
    }
    if ([self.hrefs count] != 0 ) {
        [self.hrefs removeAllObjects];
    }
    
    if ([self.postDate count] !=0 ) {
        [self.postDate removeAllObjects];
    }
    
    if ([self.replyNum count] != 0) {
        [self.replyNum removeAllObjects];
    }
    
    if ([self.author count] != 0) {
        [self.author removeAllObjects];
    }
    
    if (self.forumContentType == nil) {
        self.forumContentType = JSTL_SECTION;
    }
    
    NSString *threadURLString = [NSString stringWithFormat:@"%@/%@&page=%i",self.clServerUrl,self.forumContentType,currentPage];
//    NSLog(@"url is:%@",threadURLString);
//    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSString *response = [CLTool getCLResponseString:threadURLString andCurrentView:self.view];
//    [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    if ([response isEqualToString:@"error"] || response == nil) {
        [self performSelectorOnMainThread:@selector(openAlertView) withObject:nil waitUntilDone:NO];
        return;
    }
    NSData *data = [response dataUsingEncoding:NSUTF8StringEncoding];
    TFHpple *doc = [[TFHpple alloc] initWithHTMLData:data];
    
    //第一遍查询（帖子名称和链接地址）
    NSArray *a  =  [doc searchWithXPathQuery:@"//td[@style='text-align:left;padding-left:8px']/h3//a/text()|//td[@style='text-align:left;padding-left:8px']/h3//a|//td[@style='text-align:left;padding-left:8px']/h3/a//text()"];
//    NSArray *a  =  [doc searchWithXPathQuery:queryString];
    
    //获取所有链接的href值
     [a enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
      TFHppleElement *e = (TFHppleElement *)obj;
         if ([e objectForKey:@"href"] == nil) {
             [self.posts addObject:[e content]];
             
//             NSLog(@"post:%@ tagName:%@  className:%@",[e content],e.tagName,[e objectForKey:@"class"]);
         }else{
             [self.hrefs addObject:[e objectForKey:@"href"]];
//             NSLog(@"href: %@ tagName:%@ className:%@",[e objectForKey:@"href"],e.tagName,[e objectForKey:@"class"]);
         }
  }];
    
    //第二遍查询（作者）
//    NSArray *b = [doc searchWithXPathQuery:@"//td[@class='tal y-style']/a[@class='bl']/text()|//td[@class='tal y-style']/div/text()"];
    NSArray *b = [doc searchWithXPathQuery:@"//td[@class='tal y-style']/a[@class='bl']/text()"];
    [b enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        TFHppleElement *e = (TFHppleElement *)obj;
        if ([e objectForKey:@"class"] == nil) {
            [self.author addObject:[e content]];
        }
    }];
    
    //第三遍查询 (回帖数)
     NSArray *d = [doc searchWithXPathQuery:@"//td[@class='tal f10 y-style']/text()"];
    [d enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        TFHppleElement *e = (TFHppleElement *)obj;
        [self.replyNum addObject:[e content]];
    }];
    
    //第四遍查询 (发帖日期)
    NSArray *e = [doc searchWithXPathQuery:@"//td[@class='tal y-style']/div/text()"];
    [e enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        TFHppleElement *e = (TFHppleElement *)obj;
        [self.postDate addObject:[e content]];
    }];


 
    
    [doc release];
    [self performSelectorOnMainThread:@selector(tableviewReload) withObject:nil waitUntilDone:NO];
}

-(IBAction)nextPage
{
    if (currentPage == 359) {
        return;
    }
    currentPage++;
    MBProgressHUD *hud =   [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = [NSString stringWithFormat:@"正在打开第%i页",currentPage];
    [NSThread detachNewThreadSelector:@selector(searchesLinkText) toTarget:self withObject:nil];
    
}
-(IBAction)previousPage
{
    if (currentPage == 1) {
        return;
    }
    
    currentPage --;
    MBProgressHUD *hud =   [MBProgressHUD showHUDAddedTo:self.view animated:YES];
     hud.labelText = [NSString stringWithFormat:@"正在打开第%i页",currentPage];
    [NSThread detachNewThreadSelector:@selector(searchesLinkText) toTarget:self withObject:nil];
}
//重新加载表格
-(void)tableviewReload
{
    [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    /*
    [UIView transitionWithView:self.postsTableView
                      duration:1.0f
                       options:UIViewAnimationOptionTransitionCrossDissolve
                    animations:^(void) {
                        [self.postsTableView reloadData];
                    } completion:^(void){
                    }
     
     ];
    */
    [UIView transitionWithView:self.postsTableView duration:1.0f options:UIViewAnimationOptionTransitionCrossDissolve animations:^{
        [self.postsTableView setContentOffset:CGPointMake(0, 0) animated:NO];
            } completion:^(BOOL finished) {
                [self.postsTableView reloadData];
            }];
    
    if(currentPage == 1){
        self.previousPageButton.enabled = NO;
    }else{
        self.previousPageButton.enabled = YES;
    }
    if (currentPage == 359) {
        self.nextPageButton.enabled = NO;
    }else{
        self.nextPageButton.enabled = YES;
    }
}

-(IBAction)refreshPage
{
    [NSThread detachNewThreadSelector:@selector(searchesLinkText) toTarget:self withObject:nil];
}


-(void)openAlertView
{
    UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:@"网络访问失败"
                                                     message:@"网络访问失败，内容不能正常显示"
                                                    delegate:self
                                           cancelButtonTitle:@"OK"
                                           otherButtonTitles:nil,nil] autorelease];
    [alert show];
}

- (void)dealloc {
//    [_title release];
    [_postDate release];
    [_author release];
    [_clServerUrl release];
    [_forumContentType release];
    [_posts release];
    [_postsTableView release];
    [_previousPageButton release];
    [_nextPageButton release];
    [_toolbar release];
    [super dealloc];
}
- (void)viewDidUnload {
    [self setPreviousPageButton:nil];
    [self setNextPageButton:nil];
    [self setToolbar:nil];
    [super viewDidUnload];
}
@end
